package com.wangfugui.apprentice.common.util;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * s3 url 解析器
 */
public class S3UrlParser {

    /**
     * 解析结果封装对象
     */
    public static class S3Location {
        private final String bucket;
        private final String objectName;

        public S3Location(String bucket, String objectName) {
            this.bucket = bucket;
            this.objectName = objectName;
        }

        public String getBucket() {
            return bucket;
        }

        public String getObjectName() {
            return objectName;
        }
    }

    /**
     * 解析URL中的Bucket和ObjectName
     *
     * @param url 示例: http://localhost:9000/safe/xxx/abc/2025-05-07/xxx.png?query=param
     * @return 包含bucket和objectName的对象
     */
    public static S3Location parseUrl(String url) {
        URI uri = null;
        try {
            uri = new URI(url);
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException(url, e);
        }

        // 获取路径部分（去掉query和fragment）
        String path = uri.getPath();

        // 切分路径并过滤空字符串
        List<String> segments = Arrays.stream(path.split("/")).filter(s -> !s.isEmpty()).collect(Collectors.toList());
        if (segments.isEmpty()) {
            throw new IllegalArgumentException("Invalid URL: No bucket found");
        }

        String bucket = segments.get(0);
        String objectName = segments.size() > 1 ? String.join("/", segments.subList(1, segments.size())) : "";

        return new S3Location(bucket, objectName);
    }

}